package org.agbe;

import java.util.Date;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

public class MediaPlayerContext {

	private MediaPlayer player;
	private boolean pause;
	private Date playStartDate;

	private final Context context;

	public MediaPlayerContext(Context context) {
		this.context = context;
	}

	public MediaPlayer getPlayer() {
		return player;
	}

	public void setPlayer(MediaPlayer player) {
		this.player = player;
	}

	public Date getPlayStartDate() {
		return playStartDate;
	}

	public void setPlayStartDate(Date playStartDate) {
		this.playStartDate = playStartDate;
	}

	public void init() {
		player = new MediaPlayer();
	}

	public boolean isPlaying() {
		return player.isPlaying() || player.isLooping();
	}

	public boolean isPaused() {
		return pause;
	}

	public void playSound(Integer resourceId, int iteration) {
		try {
			playStartDate = new Date();
			player.reset();
			Uri audio = Uri.parse("android.resource://"
					+ context.getPackageName() + "/" + resourceId);
			player.setDataSource(context, audio);
			player.prepare();
			if (iteration == 0) {
				player.setLooping(true);
			} else if (iteration > 1) {
				MediaPlayerLooper looper = new MediaPlayerLooper(iteration,
						this);
				player.setOnCompletionListener(looper);
			}
			player.start();
		} catch (Exception e) {
			Log.e(AgbeGame.AGBE_LOGNAME, "Error starting media player", e);
		}
	}

	public void stopSound() {
		if (isPlaying()) {
			player.stop();
			player.setOnCompletionListener(null);
			playStartDate = null;
		}
	}

	public void pauseSound() {
		if (isPlaying()) {
			Log.d(AgbeGame.AGBE_LOGNAME, "Pausing sound");
			this.pause = true;
			player.pause();
		}
	}

	public void resumeSound() {
		if (isPaused()) {
			Log.d(AgbeGame.AGBE_LOGNAME, "Resuming sound");
			player.start();
		}
	}

}
